Given an array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
In [7]:
class Solution(object):
def singleNumber(self, nums):
"""
通过相同数字异或为0这个知识点进行操作
和0异或等于本身来初始化ans
:type nums: List[int]
:rtype: int
"""
ans = 0
for n in nums:
ans ^= n
return ans
In [8]:
Solution().singleNumber([2, 4, 5 , 5, 4])
Out[8]:
In [9]:
Solution().singleNumber([2]) # answer is 2
Out[9]:
In [ ]: